<?php
/*
+--------------------------------------------------------------------------
|   AffiliStore 2
|   ========================================
|   Web: http://www.affilistore.com
|   Email: admin (at) affilistore (dot) com
|	License Type: AffiliStore 2 is NOT open source software and limitations apply 
|   Licence Info: Visit AffiliStore website and click on 'Licence'
+--------------------------------------------------------------------------
*/
// checks to see if password session is set
// if not redirects to ../admin/
if(!$auth->getIdentity()){
	header('Location: ../index.php?case=account&act=login');
}

include_once '../includes/models/Ads.php';
include_once '../includes/models/Auth.php';
include_once '../includes/models/Account.php';
include_once '../includes/models/Program.php';


// get products database details
$getTheProdDetails = mysql_query("SELECT prodID, prodDB FROM affiliSt_products1 WHERE dbProdID = 1 ORDER BY prodDB DESC");
$theProdDetails = mysql_fetch_assoc($getTheProdDetails);
/**
 * Get authentication object to get account id
 */		
$query = "SELECT accId FROM affiliSt_accounts WHERE accUsername = '{$auth->getIdentity()}' LIMIT 1;";
try {
	$result = mysql_query($query, $databaseConnect);
	$accId = mysql_fetch_assoc($result);
	$accId = $accId['accId'];
} catch (Exception $e) {
	throw new Exception($e->getMessage() . '|' . mysql_error()); 
}
// BASE sql to insert and refresh product feed
$baseSql = "INSERT INTO affiliSt_products1 (
			
	accId,
	merchant,
	merchantProdID, 
	prodCategory,
	prodName,
	prodBrand,
	prodDescription,
	prodPromoText,
	prodLink, 
	prodImageURL,
	prodPrice,
	prodCurrency,
	prodDB,
	extraFieldA,
	extraFieldB,
	extraFieldC,
	extraFieldD,
	extraFieldE, 
	prodImageSmall, 
	dbProdID
	
	) VALUES ";
/**
 * If click "Add URL product feed" button to add new feed 
 */
if (isset($_POST['fd_updated'])) {
	// check to see if details have been completed
	if (empty($_POST['fd_feed'])) {
		$error = 1;	
	// else upload feed
	} else {
		if ($_POST['fd_csvType'] == 'tab') {
			$fd_csvType = "\t";
		} else {
			$fd_csvType = $_POST['fd_csvType'];
		}
	
		// set row variable and open file
		if ($_POST['fd_compression'] == 'gzip') {
			$handle = @fopen('compress.zlib://'.$_POST['fd_feed'], "r") or die ("<fieldset>couldn't open file</fieldset>");
		} else {
			$handle = @fopen($_POST['fd_feed'], "r") or die ("<fieldset>couldn't open file</fieldset>");
		}
		$row = 1;
		// while loop with fgetcsv sorts the csv into the data array 
		while (($data = fgetcsv($handle, 3000, $fd_csvType)) !== FALSE) {
			// display only the first row
			if ($row == 1) {
				$num = count($data);
				$data_names = array();
				for ($c=0; $c < $num; $c++) {
					$data_names[$c] = $data[$c];
				}
			}
			$row++;
		}
	}
//  ------------------------------------------- new upload feed details
} else if (isset($_POST['fd_upload'])) {

	// check to see if details have been completed
	//if (empty($_POST['feedUpload'])) {
	//$error = 1;

	// else upload feed
	//} else {


	// move file to folder on server
	$feedSource = $_FILES['feedUpload']['tmp_name'];
	$feedTarget = "../userfiles/".$_FILES['feedUpload']['name'];
		// check if file already exists
		if (file_exists($feedTarget)) {
		   echo "<fieldset>$feedTarget already exists, please rename the file you are trying to upload.</fieldset>";
		   exit;
		}
		
	move_uploaded_file($feedSource, $feedTarget) or die ("couldn't copy");
	
		if ($_POST['upload_csvType'] == 'tab') {
		$fd_csvType = "\t";
		} else {
		$fd_csvType = $_POST['upload_csvType'];
		}
	
	// set row variable and open file
	if ($_POST['upload_compression'] == 'gzip') {
	$handle = @fopen('compress.zlib://'.$feedTarget, "r") or die ("<fieldset>couldn't open file</fieldset>");
	} else {
	$handle = @fopen($feedTarget, "r") or die ("<fieldset>couldn't open file</fieldset>");
	}
	$row = 1;
		// while loop with fgetcsv sorts the csv into the data array 
		while (($data = fgetcsv($handle, 3000, $fd_csvType)) !== FALSE) {
		// display only the first row
			if ($row == 1) {
				$num = count($data);
				$data_names = array();
				for ($c=0; $c < $num; $c++) {
					$data_names[$c] = $data[$c];
				}
				
			}
		$row++;
		
		}
	//}

/**
 * This step occurred after the 2 above steps
 */
//  ------------------------------------------- new feed details
} else if (isset($_POST['URLfeed']) || isset($_POST['feedPath']) ) {
	
	/**
	 * This is uncertain and can be buggy in the feture, it can make the product to be disappear if it's actually error
	 * @todo check if this is error, I've prevent it by adding a second condition that the accId must be the same
	 */
	// remove products if merchant already exists
	$feedtest = mysql_query("SELECT prodDB FROM affiliSt_products1 WHERE prodDB = ".($theProdDetails['prodDB']+1)." AND accId = '{$accId}'") or die(mysql_error());
	if (mysql_num_rows($feedtest) > 0) {
	$empty = "DELETE FROM affiliSt_products1 WHERE prodDB IN ('".($theProdDetails['prodDB']+1)."')";
	mysql_query($sql, $databaseConnect) or die(mysql_error());
	}
	
	// start auto inc from last ID in db
	$autoinc = mysql_query("SELECT prodID FROM affiliSt_products1 ORDER BY prodDB DESC LIMIT 1");
	$autoincnum = mysql_fetch_assoc($autoinc);
	$resetautoinc = mysql_query("ALTER TABLE affiliSt_products1 AUTO_INCREMENT = ".($autoincnum['prodID']+1)."");
	
	// set row variable and open file
	$row = intval($_POST['firstRow']);
		if (isset($_POST['feedPath'])) {
			if ($_POST['compressionType'] == 'gzip') {
			$handle = fopen('compress.zlib://'.$_POST['feedPath'], "r") or die ("<fieldset>couldn't open file</fieldset>");
			} else {
			$handle = fopen($_POST['feedPath'], "r") or die ("<fieldset>couldn't open file</fieldset>");
			}
		} else {
			if ($_POST['compressionType'] == 'gzip') {
			$handle = fopen('compress.zlib://'.$_POST['URLfeed'], "r") or die ("<fieldset>couldn't open file</fieldset>");
			} else {
			$handle = fopen($_POST['URLfeed'], "r") or die ("<fieldset>couldn't open file</fieldset>");
			}
		}
	
		if ($_POST['typeFeed'] == 'tab') {
		$typeFeed = "\t";
		} else {
		$typeFeed = $_POST['typeFeed'];
		}
	
	$queries = array();
	
	
	// while loop with fgetcsv sorts the csv into the data array 
	while (($data = fgetcsv($handle, 3000, $typeFeed)) !== FALSE) {
	
		$resulta = $merchantData;
		if ($data[intval($_POST['merchantProdIDData'])] == NULL) {
			$resultb = $row;
		} else {
			$resultb = $data[intval($_POST['merchantProdIDData'])];
		}
		$resultc = ucwords(strtolower($data[intval($_POST['prodCategoryData'])]));
		$resultd = ucwords(strtolower($data[intval($_POST['prodNameData'])]));
		$resulte = ucwords(strtolower($data[intval($_POST['prodBrandData'])]));
		$resultf = $data[intval($_POST['prodDescriptionData'])];
		$resultg = $data[intval($_POST['prodPromoTextData'])];
		$resulth = $data[intval($_POST['prodLinkData'])];
		$resulti = $data[intval($_POST['prodImageURLData'])];
		$resultj = $data[intval($_POST['prodPriceData'])];
		$resultk = $_POST['prodCurrencyData'];
		$resultm = $data[intval($_POST['extraFieldAData'])];
		$resultn = $data[intval($_POST['extraFieldBData'])];
		$resulto = $data[intval($_POST['extraFieldCData'])];
		$resultp = $data[intval($_POST['extraFieldDData'])];
		$resultq = $data[intval($_POST['extraFieldEData'])];
		$resultr = $data[intval($_POST['prodImageSmallData'])];
		$results = intval($row);
		
		/**
		 * added by Kien, add ads
		 */
		
		$adsObj = new Ads();
		$authentication = $auth;
		$programObj = new Program();
		$accountObj = new Account();
		$newTextAd['text_programid'] = $programObj->getProgramIdByUserId($accountObj->getId($authentication->getIdentity()));
		$newTextAd['text_text'] = $resultg;
		$newTextAd['text_url'] = $resulth;
		$newTextAd['text_description'] = $resultf;
		$newTextAd['text_status'] = 'active';
		$newTextAd['text_image'] = $resultr;
		$adsObj->addText($newTextAd);
		$newBannerAd['banner_programid'] = $programObj->getProgramIdByUserId($accountObj->getId($authentication->getIdentity()));
		$newBannerAd['banner_url'] = $resulth;
		$newBannerAd['banner_name'] = $resulti;
		$newBannerAd['banner_status'] = 'active';
		$newBannerAd['banner_height'] = 150;
		$newBannerAd['banner_width'] = 150;
		$adsObj->addBanner($newBannerAd);
		
		if ($_POST['UrlPrefix'] == 'before'){
			$resulth = $_POST['UrlPrefixText'].$resulth;
		} else if ($_POST['UrlPrefix'] == 'after') {
			$resulth = $resulth.$_POST['UrlPrefixText'];
		}
	
		// remove characters that may interfear with navigation or display
		include("../includes/fixlist.inc.php");		
		
		$resultAccId = $accId;
		$resultc = str_replace($andAmps, "and", $resultc);
		$resultd = str_replace($andAmps, "and", $resultd);
		$resulte = str_replace($andAmps, "and", $resulte);
		$resultc = str_replace($charquotes, "", $resultc);
		$resultd = str_replace($charquotes, "", $resultd);
		$resulte = str_replace($charquotes, "", $resulte);
		$resultb = str_replace($allCharacters, "-", $resultb);
		$resultc = str_replace($allCharacters, " ", $resultc);
		$resultd = str_replace($someCharacters, " ", $resultd);
		$resulte = str_replace($allCharacters, " ", $resulte);
		$resultj = str_replace($currencyCharacters, " ", $resultj);
		$resultl = $theProdDetails['prodDB'] + 1;
	
		// miss out headers row
		if ($row != 0) {
		/**
		 * Upgrade: create insert string to insert all product in 1 queries
		 */
		// insert all the data into the database table				
		$sql = sprintf("(
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s,
			%s
			)",
			quote_smart($resultAccId),
			quote_smart($resulta),
			quote_smart($resultb),
			quote_smart($resultc),
			quote_smart($resultd),
			quote_smart($resulte),
			quote_smart($resultf),
			quote_smart($resultg),
			quote_smart($resulth),
			quote_smart($resulti),
			quote_smart($resultj),
			quote_smart($resultk),
			quote_smart($resultl),
			quote_smart($resultm),
			quote_smart($resultn),
			quote_smart($resulto),
			quote_smart($resultp),
			quote_smart($resultq),
			quote_smart($resultr),
			quote_smart($results));
			if ($row == 1)
				$queries[] = $baseSql . $sql;
			else
				$queries[] = $sql;
		}		
		$row++;
	}
	/**
	 * Execute the queries
	 */	
	$sql = implode(',', $queries);
	mysql_query($sql, $databaseConnect) or die(mysql_error());
	
	// add 1 to total product databases in config
	$sql = sprintf("UPDATE affiliSt_config SET value = %s WHERE name = 'totalDBs'",
	quote_smart($resultl));
	mysql_query($sql, $databaseConnect) or die(mysql_error());
	
	
	
	// check if csvType exists and delete 
	$result=mysql_query("SELECT * FROM affiliSt_config WHERE name='csvType".($theProdDetails['prodDB'] + 1)."'", $databaseConnect) or die(mysql_error());
	$test=mysql_fetch_assoc($result);
	if ($test['value'])
	{
	$sql= "DELETE FROM  affiliSt_config WHERE name='csvURL".($theProdDetails['prodDB'] + 1)."' or name='csvType".($theProdDetails['prodDB'] + 1)."' or name='feedMemory".($theProdDetails['prodDB'] + 1)."' or name='nav".($theProdDetails['prodDB'] + 1)."' or name='compression".($theProdDetails['prodDB'] + 1)."'" ;        
	mysql_query($sql, $databaseConnect) or die(mysql_error());
	}
	
	
	// create the new config nav
	// category listing
	$getCategory = mysql_query("SELECT prodCategory FROM affiliSt_products1 WHERE prodDB = '".($theProdDetails['prodDB'] + 1)."' ORDER BY prodCategory ASC");
	$categoryList = mysql_fetch_assoc($getCategory);
	$newnavigation = '';
	do { 
	$catresult = ucwords(strtolower($categoryList['prodCategory']));
		if ($storedCategory != $catresult && $catresult != NULL) {
		$newnavigation .= $catresult;
		// start sub nav
		// brand listing
		$getBrands = mysql_query("SELECT prodBrand FROM affiliSt_products1 WHERE prodDB = '".($theProdDetails['prodDB'] + 1)."' AND prodCategory = '$catresult' ORDER BY prodBrand ASC");
		$brandList = mysql_fetch_assoc($getBrands);
			do {
			$theresult = ucwords(strtolower($brandList['prodBrand']));
				if ($storedBrand != $theresult && $theresult != NULL) {
				$newnavigation .= '(:)'.$theresult;
				$storedBrand = $theresult;
				$brandrow++;
				} else {
				$theresult = ucwords(strtolower($brandList['prodBrand']));
				}
			} while ($brandList = mysql_fetch_assoc($getBrands));
		$storedCategory = $catresult;
		$newnavigation .= '-:-';
		} else {
		$catresult = ucwords(strtolower($categoryList['prodCategory']));
		}
	} while ($categoryList = mysql_fetch_assoc($getCategory));
	$newnavigation = rtrim($newnavigation, '-:-');
	// end config nav
	
	// create selection memory for admin refresh
	if (isset($_POST['feedPath'])) {
	$handle = $_POST['feedPath'];
	$whichFeed = 'Upload Feed';
	} else {
	$handle = $_POST['URLfeed'];
	$whichFeed = 'URL Feed';
	}
	
	// move image file to folder on server
	$logoSource = $_FILES['logoUpload']['tmp_name'];
		if ($logoSource != NULL) {
		$id = $auth->getIdentity();
		$logoTarget = "userfiles/merchant/".$id.'_'.$_FILES['logoUpload']['name'];
		move_uploaded_file($logoSource, '../'.$logoTarget) or die ("couldn't copy");
		} else {
		$logoTarget = '';
		}
	
	
	$insert = array (
			array ( 'name' =>  'feedMemory'.($theProdDetails['prodDB'] + 1),
					'value' => $merchantData.'-:-'.intval($merchantProdIDData).'-:-'.intval($prodCategoryData).'-:-'.intval($prodNameData).'-:-'.intval($prodBrandData).'-:-'.intval($prodDescriptionData).'-:-'.intval($prodPromoTextData).'-:-'.intval($prodLinkData).'-:-'.intval($prodImageURLData).'-:-'.intval($prodPriceData).'-:-'.$prodCurrencyData.'-:-'.$_POST['firstRow'].'-:-'.$_POST['UrlPrefix'].'-:-'.$_POST['UrlPrefixText'].'-:-'.intval($extraFieldAData).'-:-'.intval($extraFieldBData).'-:-'.intval($extraFieldCData).'-:-'.intval($extraFieldDData).'-:-'.intval($extraFieldEData).'-:-'.$merchantProdIDTitle.'-:-'.$prodCategoryTitle.'-:-'.$prodNameTitle.'-:-'.$prodBrandTitle.'-:-'.$prodDescriptionTitle.'-:-'.$prodPromoTextTitle.'-:-'.$prodLinkTitle.'-:-'.$prodImageURLTitle.'-:-'.$prodPriceTitle.'-:-'.$extraFieldATitle.'-:-'.$extraFieldBTitle.'-:-'.$extraFieldCTitle.'-:-'.$extraFieldDTitle.'-:-'.$extraFieldETitle.'-:-'.$logoTarget.'-:-'.intval($prodImageSmallData),
					'comment' => 'Remembers which feed columns have been put into AffiliStore columns',
					'title' => 'Feed Memory'),
			array ( 'name' =>  'csvURL'.($theProdDetails['prodDB'] + 1),
					'value' => $handle,
					'comment' => 'The link to your product feed',
					'title' => $whichFeed),
			array ( 'name' =>  'csvType'.($theProdDetails['prodDB'] + 1),
					'value' => $_POST['typeFeed'],
					'comment' => 'The format of the product field eg. comma seperated, xml etc.',
					'title' => 'Product Feed Type'),
			array ( 'name' =>  'nav'.($theProdDetails['prodDB'] + 1),
					'value' => $newnavigation,
					'comment' => 'Category and subcategory navigation',
					'title' => 'Generated Navigation'),
			array ( 'name' =>  'compression'.($theProdDetails['prodDB'] + 1),
					'value' => $_POST['compressionType'],
					'comment' => 'Type of compression used for feed',
					'title' => 'Compression Type'),
			array ( 'name' =>  'accId'.($theProdDetails['prodDB'] + 1),
					'value' => $accId,
					'comment' => 'Feed belong to this account ID',
					'title' => 'Feed Owner ID')
	);
		
		// insert values posted from Step 1 into config table
	foreach ($insert as $row) {
		$sql = sprintf("INSERT INTO affiliSt_config (
				name, value, comment, title
				) values (
				%s, %s, %s, %s
				)",
				quote_smart($row['name']),
				quote_smart($row['value']),
				quote_smart($row['comment']),
				quote_smart($row['title']));
		mysql_query($sql, $databaseConnect) or die(mysql_error());
	}
// ------------------------------------------- refresh product feed
} else if (isset($_GET['fd_refresh'])) {
	/**
	 * Check if the user trying to refresh a feed not associate with his merchant account
	 */
	$myCheck = mysql_query("SELECT COUNT(*) FROM affiliSt_config WHERE value = {$accId} AND name = 'accId{$_GET['fd_refresh']}'") or die(mysql_error());
	$myCheck = mysql_fetch_array($myCheck);
	$myCheck = $myCheck[0];	
	if (!$myCheck){
		echo '<fieldset><strong style="color:red">You about to refresh a wrong feed\'s ID</strong></fieldset>';
	}
	else {
		$fdrefresh = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'feedMemory".$_GET['fd_refresh']."'");
		$refresh = mysql_fetch_assoc($fdrefresh);
		
		$pieces = explode("-:-", $refresh['value']);
			
		$fdURLfeed = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'csvURL".$_GET['fd_refresh']."'");
		$URLfeed = mysql_fetch_assoc($fdURLfeed);
		$fdtypeFeed = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'csvType".$_GET['fd_refresh']."'");
		$typeFeed = mysql_fetch_assoc($fdtypeFeed);
		$fdcompressionFeed = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'compression".$_GET['fd_refresh']."'");
		$compressionFeed = mysql_fetch_assoc($fdcompressionFeed);		
		$fdAccIdFeed = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'accId{$_GET['fd_refresh']}'");
		
		$accIdFeed = mysql_fetch_assoc($fdAccIdFeed);
			if ($typeFeed['value'] == 'tab') {
			$typeFeed = "\t";
			} else {
			$typeFeed = $typeFeed['value'];
			}
		
		// set row variable and open file
		$row = intval($pieces[11]);
			if ($compressionFeed['value'] == 'gzip') {
			$handle = fopen('compress.zlib://'.$URLfeed['value'], "r");
			} else {
			$handle = fopen($URLfeed['value'], "r");
			}
		
		// empty the table
		$empty = "DELETE FROM affiliSt_products1 WHERE prodDB IN ('".$_GET['fd_refresh']."')";
		mysql_query($empty);
		
		// start auto inc from last ID in db
		$autoinc = mysql_query("SELECT prodID FROM affiliSt_products1 ORDER BY prodDB DESC LIMIT 1");
		$autoincnum = mysql_fetch_assoc($autoinc);
		$resetautoinc = mysql_query("ALTER TABLE affiliSt_products1 AUTO_INCREMENT = ".($autoincnum['prodID']+1)."");
		$queries = array();
		// while loop with fgetcsv sorts the csv into the data array 
		while (($data = fgetcsv($handle, 3000, $typeFeed)) !== FALSE) {
		
			$resulta = $pieces[0];
			if ($data[intval($pieces[1])] == NULL) {
			$resultb = $row;
			} else {
			$resultb = $data[intval($pieces[1])];
			}
			$resultb = $data[intval($pieces[1])];
			$resultc = ucwords(strtolower($data[intval($pieces[2])]));
			$resultd = ucwords(strtolower($data[intval($pieces[3])]));
			$resulte = ucwords(strtolower($data[intval($pieces[4])]));
			$resultf = $data[intval($pieces[5])];
			$resultg = $data[intval($pieces[6])];
			$resulth = $data[intval($pieces[7])];
			$resulti = $data[intval($pieces[8])];
			$resultj = $data[intval($pieces[9])];
			$resultk = $pieces[10];
			$resultm = $data[intval($pieces[14])];
			$resultn = $data[intval($pieces[15])];
			$resulto = $data[intval($pieces[16])];
			$resultp = $data[intval($pieces[17])];
			$resultq = $data[intval($pieces[18])];
			$resultr = $data[intval($pieces[34])];
			$results = intval($row);
			
			if ($pieces[12] == 'before') {
			$resulth = $pieces[13].$resulth;
			} else if ($pieces[12] == 'after') {
			$resulth = $resulth.$pieces[13];
			}
		
		// remove characters that may interfear with navigation or display
			include("../includes/fixlist.inc.php");
			$resultAccId = $accIdFeed['value'];
			$resultc = str_replace($andAmps, "and", $resultc);
			$resultd = str_replace($andAmps, "and", $resultd);
			$resulte = str_replace($andAmps, "and", $resulte);
			$resultc = str_replace($charquotes, "", $resultc);
			$resultd = str_replace($charquotes, "", $resultd);
			$resulte = str_replace($charquotes, "", $resulte);
			$resultb = str_replace($allCharacters, "-", $resultb);
			$resultc = str_replace($allCharacters, " ", $resultc);
			$resultd = str_replace($someCharacters, " ", $resultd);
			$resulte = str_replace($allCharacters, " ", $resulte);
			$resultj = str_replace($currencyCharacters, " ", $resultj);
			$resultl = $_GET['fd_refresh'];
		
		// miss out headers row
		   if ($row != 0) {
		   // insert all the data into the database table
				$sql = sprintf("(
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s,
					%s
					)",
					quote_smart($resultAccId),
					quote_smart($resulta),
					quote_smart($resultb),
					quote_smart($resultc),
					quote_smart($resultd),
					quote_smart($resulte),
					quote_smart($resultf),
					quote_smart($resultg),
					quote_smart($resulth),
					quote_smart($resulti),
					quote_smart($resultj),
					quote_smart($resultk),
					quote_smart($resultl),
					quote_smart($resultm),
					quote_smart($resultn),
					quote_smart($resulto),
					quote_smart($resultp),
					quote_smart($resultq),
					quote_smart($resultr),
					quote_smart($results));
					if ($row == 1)
						$queries[] = $baseSql . $sql;
					else
						$queries[] = $sql;
			}
			$row++;
		}
		/**
		 * Execute the queries
		 */	
		$sql = implode(',', $queries);
		mysql_query($sql, $databaseConnect) or die(mysql_error());
		
		// create the new config nav
		// category listing
		$getCategory = mysql_query("SELECT prodCategory FROM affiliSt_products1 WHERE prodDB = '".$_GET['fd_refresh']."' ORDER BY prodCategory ASC");
		$categoryList = mysql_fetch_assoc($getCategory);
		$newnavigation = '';
		do { 
		$catresult = ucwords(strtolower($categoryList['prodCategory']));
			if ($storedCategory != $catresult && $catresult != NULL) {
			$newnavigation .= $catresult;
			// start sub nav
			// brand listing
			$getBrands = mysql_query("SELECT prodBrand FROM affiliSt_products1 WHERE prodDB = '".$_GET['fd_refresh']."' AND prodCategory = '$catresult' ORDER BY prodBrand ASC");
			$brandList = mysql_fetch_assoc($getBrands);
				do {
				$theresult = ucwords(strtolower($brandList['prodBrand']));
					if ($storedBrand != $theresult && $theresult != NULL) {
					$newnavigation .= '(:)'.$theresult;
					$storedBrand = $theresult;
					$brandrow++;
					} else {
					$theresult = ucwords(strtolower($brandList['prodBrand']));
					}
				} while ($brandList = mysql_fetch_assoc($getBrands));
			$storedCategory = $catresult;
			$newnavigation .= '-:-';
			} else {
			$catresult = ucwords(strtolower($categoryList['prodCategory']));
			}
		} while ($categoryList = mysql_fetch_assoc($getCategory));
		$newnavigation = rtrim($newnavigation, '-:-');
		
		$sql= "DELETE FROM affiliSt_config WHERE name='nav".$_GET['fd_refresh']."'" ;        
		mysql_query($sql, $databaseConnect) or die(mysql_error());
		$insert = array (
				array ( 'name' =>  'nav'.$_GET['fd_refresh'],
						'value' => $newnavigation,
						'comment' => 'Category and subcategory navigation',
						'title' => 'Generated Navigation')
		);
			
		// insert values posted from Step 1 into config table
		foreach ($insert as $row) {
			$sql = sprintf("INSERT INTO affiliSt_config (
					name, value, comment, title
					) values (
					%s, %s, %s, %s
					)",
					quote_smart($row['name']),
					quote_smart($row['value']),
					quote_smart($row['comment']),
					quote_smart($row['title']));
			mysql_query($sql, $databaseConnect) or die(mysql_error());
		}
		// end config nav
		
		echo '<fieldset><strong style="color:green">Product Feed Refreshed</strong></fieldset>';
	}
// ------------------------------------------- delete product feed
} else if (isset($_GET['fd_delete'])) {
	/**
	 * Check if the user trying to refresh a feed not associate with his merchant account
	 */	
	$myCheck = mysql_query("SELECT COUNT(*) FROM affiliSt_config WHERE value = {$accId} AND name = 'accId{$_GET['fd_delete']}'") or die(mysql_error());
	$myCheck = mysql_fetch_array($myCheck);
	$myCheck = $myCheck[0];	
	if (!$myCheck){
		echo '<fieldset><strong style="color:red">You about to delete a wrong feed\'s ID</strong></fieldset>';
	}
	else
	{
		// delete uploaded file
		$fdURLfeed = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'csvURL".$_GET['fd_delete']."'");
		$URLfeed = mysql_fetch_assoc($fdURLfeed);
			if ($URLfeed['title'] == 'Upload Feed') {
			unlink($URLfeed['value']);
			}
		
		// delete the products and settings db
		$empty = "DELETE FROM affiliSt_products1 WHERE prodDB IN ('".$_GET['fd_delete']."')";
		mysql_query($empty);
		$empty = "DELETE FROM affiliSt_config WHERE name IN ('csvURL".$_GET['fd_delete']."', 'feedMemory".$_GET['fd_delete']."', 'csvType".$_GET['fd_delete']."', 'nav".$_GET['fd_delete']."', 'compression".$_GET['fd_delete']."', 'accId".$_GET['fd_delete']."')";
		mysql_query($empty);		
	}
}

$getUserDetails = mysql_query("SELECT * FROM affiliSt_config");
$userDetails = mysql_fetch_assoc($getUserDetails);
?>

<?php
// error report
if ($error == 1) {
echo '<fieldset><strong style="color:red">ERROR: Fields must not be empty</strong></fieldset>';
exit;
}
if (isset($_POST['URLfeed'])) {
echo '<fieldset><strong style="color:green">Product Feed Added</strong></fieldset>';
}
?>

<fieldset>
<legend>Add a Product Feed</legend>

<form enctype="multipart/form-data" action="userpanel.php?ad=fd" method="post" name="updateDetails">
<?php
if (isset($_POST['fd_updated']) || isset($_POST['fd_upload'])) { ?>

	<p>Please match the sample first row from the <strong>product feed</strong> columns with the <strong>AffiliStore</strong> database columns:</p>
	
	<table border="0" cellpadding="4" cellspacing="0" width="100%" style="border-top:1px solid #cccccc;">
		<tr>
			<th align="left" style="border-bottom:1px solid #cccccc;">Product feed</th>
			<th align="left" style="border-bottom:1px solid #cccccc;">&nbsp;</th>
			<th align="left" style="border-bottom:1px solid #cccccc;">AffiliStore</th>
			<th align="left" style="border-bottom:1px solid #cccccc;">Title</th>
		</tr>
	
<?php
	//Get names of columns in table
	$field_names = array('merchant', 'merchantProdID', 'prodCategory', 'prodName', 'prodBrand', 'prodDescription', 'prodPromoText', 'prodLink', 'prodImageURL', 'prodImageSmall', 'extraFieldA', 'extraFieldB', 'extraFieldC', 'extraFieldD', 'extraFieldE', 'prodPrice');

	$totalCols = count($field_names);
	for ($ab=0; $ab < $totalCols; $ab++) {
			
		if ($field_names[$ab] == 'merchant') {
		$ascolname = 'Merchant Name';
		} else if ($field_names[$ab] == 'merchantProdID') {
		$ascolname = 'Merchant Product ID';
		} else if ($field_names[$ab] == 'prodCategory') {
		$ascolname = 'Product Category';
		} else if ($field_names[$ab] == 'prodName') {
		$ascolname = 'Product Name';
		} else if ($field_names[$ab] == 'prodBrand') {
		$ascolname = 'Product Brand';
		} else if ($field_names[$ab] == 'prodDescription') {
		$ascolname = 'Product Description';
		} else if ($field_names[$ab] == 'prodPromoText') {
		$ascolname = 'Promotional Text';
		} else if ($field_names[$ab] == 'prodLink') {
		$ascolname = 'Affiliate Product Link';
		} else if ($field_names[$ab] == 'prodImageURL') {
		$ascolname = 'Product Image URL';
		} else if ($field_names[$ab] == 'prodImageSmall') {
		$ascolname = 'Product Small Image URL';
		} else if ($field_names[$ab] == 'prodPrice') {
		$ascolname = 'Product Price';
		} else if ($field_names[$ab] == 'extraFieldA') {
		$ascolname = 'Extra Field A';
		} else if ($field_names[$ab] == 'extraFieldB') {
		$ascolname = 'Extra Field B';
		} else if ($field_names[$ab] == 'extraFieldC') {
		$ascolname = 'Extra Field C';
		} else if ($field_names[$ab] == 'extraFieldD') {
		$ascolname = 'Extra Field D';
		} else if ($field_names[$ab] == 'extraFieldE') {
		$ascolname = 'Extra Field E';
		}
		
		if ($ab == 0) {
			echo '<tr><td align="left" style="border-bottom:1px solid #cccccc;">';
			echo '<input type="text" value="eg. Amazon" id="'.$field_names[$ab].'" name="'.$field_names[$ab].'Data" onfocus="this.value=\'\'" />';	
			echo '</td>';
		
		} else {

			echo '<tr><td align="left" style="border-bottom:1px solid #cccccc;"><select id="'.$field_names[$ab].'" name="'.$field_names[$ab].'Data">
		   	<option selected="selected" value="999999">Please Choose...</option>'."\n";
	   	
			$totalFields = count($data_names);
 			for ($ac=0; $ac < $totalFields; $ac++) {
			// limit characters to 50
			$t = substr($data_names[$ac], 0, 50);
				echo '<option value="'.$ac.'">'.$t.'</option>'."\n";
			}
			
			echo '</select></td>';
		}
		
		echo '<td align="left" style="border-bottom:1px solid #cccccc;"><img src="images/arrow1.gif" width="23" height="23" alt="" /></td>
		<td align="left" style="border-bottom:1px solid #cccccc;"><label for="'.$field_names[$ab].'">'.$ascolname.'</label></td>'."\n";
	
		if ($ab == 0) {
			echo '<td align="left" style="border-bottom:1px solid #cccccc;">';
			echo 'Logo: <input type="file" name="logoUpload" />';	
			echo '</td>'."\n";
		} else if ($ab == 7 || $ab == 8 || $ab == 9) {
			echo '<td align="left" style="border-bottom:1px solid #cccccc;">';
			echo '&nbsp;';	
			echo '</td>'."\n";
		} else {
			echo '<td align="left" style="border-bottom:1px solid #cccccc;">';
			echo '<input type="text" value="" name="'.$field_names[$ab].'Title" />';	
			echo '</td>'."\n";
		}
   	}

	echo '</tr>';
	echo '<td align="left" style="border-bottom:1px solid #cccccc;"><input type="text" value="$" id="prodCurrency" name="prodCurrencyData" /></td>
		<td align="left" style="border-bottom:1px solid #cccccc;"><img src="images/arrow1.gif" width="23" height="23" alt="" /></td>
		<td align="left" style="border-bottom:1px solid #cccccc;"><label for="prodCurrency">Product Currency</label></td>
		<td>&nbsp;</td></tr>';
	
	echo '</table>
	
	<p><label for="row">Miss out first row of product feed (Yes if headers)? <select id="row" name="firstRow">
			<option selected="selected" value="0">Yes</option>
			<option value="1">No</option>
			</select></label></p>
			
	<p><label for="prefix">Add a URL prefix to Affiliate Product Link? <select id="prefix" name="UrlPrefix">
			<option selected="selected" value="0">No</option>
			<option value="before">Yes, Before Link</option>
			<option value="after">Yes, After Link</option>
			</select></label><input name="UrlPrefixText" type="text" class="adminInput" /></p>
	
	<p>Please note: you must try and match as many columns as possible for the website to be built correctly.</p>
	
	
	<input type="submit" value="Add Product Feed" class="padSubmit" />';
	if (!isset($_POST['fd_upload'])) {
		echo '<input type="hidden" name="URLfeed" value="'.$fd_feed.'" />';
		echo '<input type="hidden" name="typeFeed" value="'.$fd_csvType.'" />';
		echo '<input type="hidden" name="compressionType" value="'.$fd_compression.'" />';
	} else {
		echo '<input type="hidden" name="feedPath" value="'.$feedTarget.'" />';
		echo '<input type="hidden" name="typeFeed" value="'.$upload_csvType.'" />';
		echo '<input type="hidden" name="compressionType" value="'.$upload_compression.'" />';
	}
	echo '</fieldset>
	</form>';
} else { ?>
	</form>
	
	<?php 
	// check to see if upload folder is writable
	$filename = '../userfiles/';
	if (!is_writable($filename)) {
	   echo('<p>Please change the file permissions to <strong>777</strong> for the following folder: <strong>userfiles/</strong></p>
	   <p>This will allow AffiliStore to upload product feeds from you computer.</p>');
	} else {
?>
	
		<form enctype="multipart/form-data" action="userpanel.php?ad=fd" method="post" name="uploadDetails">
		<table cellpadding="4" cellspacing="0" border="0">
		<tr>
		<td><label for="upload_a_file">Upload Product Feed File:</label></td>
		<td><input type="file" name="feedUpload" id="upload_a_file" /></td>
		</tr>
		<tr>
		<td>
		<label for="uploadCsvType">Select Feed Type:</label>
		</td>
		<td>
		<select name="upload_csvType" id="uploadCsvType" class="adminInput">
		<option value=",">CSV (comma)</option>
		<option value="|">CSV (pipe)</option>
		<option value="tab">CSV (tab)</option>
		</select>
		</td>
		</tr>
		<tr>
		<td>
		<label for="fdCsvType">Select Compression Type:</label>
		</td>
		<td>
		<select name="upload_compression" id="uploadCompression" class="adminInput">
		<option value="none">None</option>
		<option value="gzip">gzip</option>
		</select>
		</td>
		</tr>
		</table>
		<input type="hidden" name="fd_upload" value="1" />
		<input type="submit" value="Upload Product Feed" class="padSubmit" />
		</form>
<?php 
	}
} 
?>

</fieldset>


<fieldset>
<legend>Manage Product Feeds</legend>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tr>
<th align="left" valign="top">Id</th>
<th align="left" valign="top">Feed Type</th>
<th align="left" valign="top">Refresh/Cron Refresh Link/Delete</th>
</tr>
<?php
$getTheProdDetails = mysql_query("SELECT prodID, prodDB FROM affiliSt_products1 WHERE dbProdID = 1 AND accId = '{$accId}' ORDER BY prodDB DESC");
$theProdDetails = mysql_fetch_assoc($getTheProdDetails);
if ($theProdDetails['prodID'] != NULL) {
$getProdDBs = mysql_query("SELECT * FROM affiliSt_products1 WHERE dbProdID = 1 AND accId = '{$accId}' ORDER BY prodDB ASC");
$prodDBs = mysql_fetch_assoc($getProdDBs);

	do {
		$dbsResult = $prodDBs['prodDB'];
		
		// get confid details
		$getProdDBsConfig = mysql_query("SELECT * FROM affiliSt_config WHERE name = 'csvURL".$dbsResult."'");
		$prodDBsConfig = mysql_fetch_assoc($getProdDBsConfig);
		if ($storedDBs != $dbsResult) {
		echo('<tr>
				<td style="border-top:1px solid #cccccc">'.$prodDBs['prodID'].'</td>
				<td style="border-top:1px solid #cccccc"><span title="'.$prodDBsConfig['value'].'">'.$prodDBsConfig['title'].'</span></td>
				<td style="border-top:1px solid #cccccc">[<a href="userpanel.php?ad=fd&fd_refresh='.$dbsResult.'">Refresh</a>] [<a href="includes/cronrefresh.php?fd_refresh='.$dbsResult.'" title="'.$installDir['value'].'admin/includes/cronrefresh.php?fd_refresh='.$dbsResult.'" target="_blank">Cron Refresh Link</a>] [<a href="userpanel.php?ad=fd&fd_delete='.$dbsResult.'">Delete</a>]</td>
				<td style="border-top:1px solid #cccccc"></td></tr>');
		$storedDBs = $dbsResult;
		} else {
		$dbsResult = $prodDBs['prodDB'];
		}
	} while ($prodDBs = mysql_fetch_assoc($getProdDBs));
	
}
?>
</tr>
</table>
</fieldset>